<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="110px" @submit.native.prevent>
      <el-form-item label="聊天背景名称" prop="name">
        <el-input
          v-model="queryParams.name"
          placeholder="请输入聊天背景名称"
          clearable
          @clear="handleQuery"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['human:chatBackgroundMusic:add']"
        >新增</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="chatBackgroundMusicList">
      <el-table-column label="聊天背景名称" align="center" prop="name" :show-overflow-tooltip="true" width="200" fixed/>
      <el-table-column label="文件地址" align="center" prop="fileUrl" width="300" :show-overflow-tooltip="true">
        <template slot-scope="scope">
          <i class="el-icon-document-copy" v-clipboard:copy="scope.row.fileUrl" v-clipboard:success="copyText" style="margin-right: 5px;cursor: pointer;"></i>
          {{ scope.row.fileUrl }}
        </template>
      </el-table-column>
      <el-table-column label="样式类型" align="center" prop="styleName" width="200"/>
      <el-table-column label="参数" align="center" prop="param" width="200" />
      <el-table-column label="描述" align="center" prop="remark" />
      <el-table-column label="创建时间" align="center" prop="createTime" width="180">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.createTime)}}</span>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width" fixed="right">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['human:chatBackgroundMusic:edit']"
          >编辑</el-button>
          <el-button
            size="mini"
            type="text"
            @click="handleDelete(scope.row)"
            v-hasPermi="['human:chatBackgroundMusic:remove']"
          >删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />
    <!-- 添加或修改发音人对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="50%" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" @submit.native.prevent>
        <el-row>
          <el-col :span="18">
            <el-col :span="16">
              <el-form-item label="聊天背景名称:" prop="name" label-width="120px">
                <el-input v-model="form.name" size= "small" placeholder="请输入发音人名称"/>
              </el-form-item>
            </el-col>
          </el-col>
          <el-col :span="18">
            <el-col :span="16">
              <el-form-item label="video文件:" prop="fileUrl" label-width="120px">
                <div class="music_img" v-if="form.fileUrl != null && form.fileUrl != '' ">
                  <audio :src="form.fileUrl" controls style="width: 600px;height: 30px"></audio>
                </div>
                <el-upload
                  class="upload-template"
                  ref="upload"
                  drag
                  :action="uploadUrl"
                  :limit="1"
                  :show-file-list="false"
                  :before-upload="handleBeforeUpload"
                  :on-success="handleUploadSuccess"
                  :on-error="handleUploadError"
                  :on-progress="uploadVideoProcess"
                  :headers="headers">
                  <i class="el-icon-upload"></i>
                  <!-- 进度条 -->
                  <el-progress v-if="progressFlag" :percentage="loadProgress"></el-progress>
                  <div class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div>
                  <div class="el-upload__tip" slot="tip" style="margin-top: -20px">上传图片只能语音格式  !</div>
                </el-upload>
              </el-form-item>
            </el-col>
          </el-col>
          <el-col :span="24">
            <el-form-item label="类别:" prop="styleUid" label-width="120px">
              <el-select v-model="form.styleUid" placeholder="请选择类别">
                <el-option
                  v-for="item in this.speakerTypeList"
                  :key="item.uid"
                  :label="item.styleName"
                  :value="item.uid">
                </el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="参数:" prop="param" label-width="120px">
              <el-input type= "textarea" v-model="form.param" :rows="4"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="描述信息:" prop="remark" label-width="120px">
              <el-input type= "textarea" v-model="form.remark" :rows="4"></el-input>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <div slot="footer" class="dialog-footer" style="margin-top: -50px">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import {listChatBackgroundMusic, insertChatBackgroundMusic, selectChatBackgroundMusic, updateChatBackgroundMusic, deleteChatBackgroundMusic} from "@/api/platform/human/chatBackgroundMusic";
import {listSpeakerTypeInfo} from "@/api/platform/human/speakerType";
import {getToken} from "@/utils/auth";

export default {
  name: "chatBackgroundMusic",
  data() {
    let checkParam = (rule, value, callback) => {
      try {
        if(value != ""){
          let obj = JSON.parse(value)
          if(typeof obj == 'object' && obj){
            callback();
          }
        }
        callback();
      }catch(error){
        return callback(new Error('接口参数格式错误'));
      }
    };
    return {
      loadProgress: 0, // 动态显示进度条
      progressFlag: false, // 关闭进度条
      uploadUrl: process.env.VUE_APP_BASE_API + "/system/file/upload", // 上传的图片服务器地址
      headers: {
        Authorization: "Bearer " + getToken()
      },
      // 遮罩层
      loading: true,
      // 显示搜索条件
      showSearch: true,
      chatBackgroundMusicList: [],
      speakerTypeList: [],
      // 总条数
      total: 0,
      // 弹出层标题
      title: "",
      detailOpen: false,
      // 是否显示添加修改弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
      },
      // 表单参数
      form: {
      },
      // 表单校验
      rules: {
        name: [
          { required: true, message: "应用名称不能为空", trigger: "blur" }
        ],
        styleUid:[
          { required: true, message: "发音人类别不能为空", trigger: "blur" }
        ],
        param: [
          { validator: checkParam, trigger: "blur" },
          { required: false, message: "接口参数信息不能为空", trigger: "blur" }
        ]
      }
    };
  },
  created() {
    this.getList();
  },
  methods: {
    /** 查询模板列表 */
    getList() {
      this.loading = true;
      listChatBackgroundMusic(this.queryParams).then(response => {
        this.chatBackgroundMusicList = response.rows;
        this.total = response.total;
        this.loading = false;
      })
    },
    // 上传前校检格式和大小
    handleBeforeUpload(file) {
      const type = ["audio/mpeg", "audio/wav"];
      const isJPG = type.includes(file.type);
      // 检验文件格式
      if (!isJPG) {
        this.$message.error(`文件格式错误!`);
        return false;
      }
      const isLt = ((file.size / 1024 / 1024) < 1);
      if (!isLt) {
        this.$message.error(`上传文件大小不能超过 1 MB!`);
        return false;
      }
      return true;
    },
    uploadVideoProcess(event, file, fileList) {
      this.progressFlag = true; // 显示进度条
      this.loadProgress = parseInt(event.percent); // 动态获取文件上传进度
      if (this.loadProgress >= 100) {
        this.loadProgress = 100
        setTimeout( () => {this.progressFlag = false}, 1000) // 一秒后关闭进度条
      }
    },
    handleUploadSuccess(res, file) {
      // 如果上传成功
      if (res.code == 200) {
        this.form.fileUid = res.data.uid;
        this.form.fileUrl = res.data.url;
        this.$message.success("上传成功");
        this.$refs.upload.clearFiles()
      } else {
        this.$message.error("上传失败");
      }
    },
    handleUploadError() {
      this.$message.error("上传失败");
    },
    copyText(){
      this.$message.success("复制成功")
    },

    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.speakerTypeList = []
      this.form = {};
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加背景音乐配置";
      this.selectSpeakerInfoList();
    },
    selectSpeakerInfoList(){
      //参数直接默认查询1000条
      let param = {};
      param.pageNum = 1;
      param.pageSize = 1000;
      param.type=1
      listSpeakerTypeInfo(param).then(response =>{
        this.speakerTypeList = response.rows
      })
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      this.open = true;
      this.title = "编辑背景音乐配置";
      this.selectSpeakerInfoList();
      selectChatBackgroundMusic(row.uid).then(response =>{
        this.form = response.data;
        if(this.form.param != null){
          this.form.param = JSON.stringify(JSON.parse(this.form.param), null, 2);
        }
      })

    },
    /** 提交按钮 */
    submitForm: function() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.form.uid == undefined) {
            insertChatBackgroundMusic(this.form).then(response => {
              this.$modal.msgSuccess("添加成功");
              this.open = false;
              this.getList();
            })
          }else{
            let data = this.form;
            //提示
            const message = "<div>确定要修改配置信息？</div>"
            this.$modal.confirm(message).then(function() {
              return updateChatBackgroundMusic(data);
            }).then(() => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            })
          }
        }
      })
    },

    /** 删除按钮操作 */
    handleDelete(row) {
      let data = {}
      data.uid = row.uid;
      //提示
      const message = "<div>确定要删除应用: <span>" + row.name + " ?</span></div>"+
        "<span style='margin-top: 20px'>应用ID:</span> &nbsp;&nbsp;&nbsp;" + row.uid
      this.$modal.confirm(message).then(function() {
        return deleteChatBackgroundMusic(data);
      }).then(() => {
        this.$modal.msgSuccess("删除成功");
        this.getList()
      })
    },
  }
};
</script>

<style scoped>
/deep/ .el-textarea__inner {
  resize: none;
}
.sound_info{
  background: rgba(240, 240, 240, 0.5);
  filter: Alpha(opacity=20);
}
.music_img:hover{
  cursor: pointer;
}

</style>
